package com.module.user.ui.login

import android.os.Bundle
import android.text.Editable
import android.text.TextPaint
import android.text.TextUtils
import android.text.TextWatcher
import android.text.style.ClickableSpan
import android.view.View
import androidx.core.content.ContextCompat
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.common.app.base.AppActivity
import com.common.app.core.RouterHub
import com.common.app.data.api.ApiConstant
import com.common.app.data.bean.CommonMessageRelayModel
import com.common.app.data.bean.KeyBundle
import com.common.app.data.bean.KeyPre
import com.common.app.helper.LaunchHelper
import com.common.app.utls.Constants
import com.common.app.utls.HeadTitleUtils
import com.common.base.app.extras.no
import com.common.base.app.extras.otherwise
import com.common.base.app.extras.setOnClickListener
import com.common.base.app.extras.showToast
import com.common.base.app.extras.startActivity
import com.common.base.app.extras.yes
import com.common.base.utils.DebugUtils.isDebugModel
import com.common.base.utils.SpUtilsManagement
import com.common.base.utils.StatusBarUtils
import com.common.base.utils.ToastUtils
import com.module.user.R
import com.module.user.databinding.UserActivityLoginBinding
import com.zrq.spanbuilder.Spans

/**
 * 作者：sosou
 * <p>
 * 版本：1.0
 * <p>
 * 创建日期：2022/9/2
 * <p>
 * 描述：登录注册主页面
 * <p>
 * 修订历史：
 */
@Route(path = RouterHub.ROUTER_LOGIN_ACTIVITY)
class LoginActivity : AppActivity<UserActivityLoginBinding, LoginViewModel>(),View.OnClickListener {

    override fun getViewModel() = LoginViewModel::class.java

    override fun getViewContentBinding() = UserActivityLoginBinding.inflate(layoutInflater)

    override fun isStatusBarTranslate(): Boolean = true
    override fun isShowToolBar(): Boolean = false

    @Autowired(name = KeyBundle.BUNDLE_KEY)
    @JvmField
    var commonMessageRelayModel: CommonMessageRelayModel? = null

    var mPhone: String = ""
    var mCountry: String = "+86"
    var authType: Int = 1

    override fun initViews() {
        super.initViews()
        StatusBarUtils.setStatusBarHeight(mViewContentBinding.statusView)
        StatusBarUtils.setStatusBarForegroundColor(this, true)

        val headTitleUtils = HeadTitleUtils(this)
        headTitleUtils.setTitle("")
        headTitleUtils.setLineStyle(10)
    }

    override fun lazyInitData() {
        super.lazyInitData()

        SpUtilsManagement.getString(KeyPre.KEY_USER_PHONE, mPhone).let {
            mViewContentBinding.phoneEdt.setText(it)
        }

        mViewContentBinding.privacyAgreementCkbHint.text = Spans.builder()
            .text("我已同意")
            .text("《用户协议》")
            .click(mViewContentBinding.privacyAgreementCkbHint, object : ClickableSpan() {
                override fun onClick(widget: View) {
                    //                        PToastUtils.t("用户协议");
                    LaunchHelper.launchWebActivity(
                        ApiConstant.SERVICE_AGREEMENT_SERVER
                    )
                }

                override fun updateDrawState(ds: TextPaint) {
                    ds.color = ContextCompat.getColor(this@LoginActivity, R.color.c_3378ff)
                    ds.isUnderlineText = false
                }
            })
            .text("和")
            .text("《隐私保护协议》")
            .click(mViewContentBinding.privacyAgreementCkbHint, object : ClickableSpan() {
                override fun onClick(widget: View) {
                    //                        PToastUtils.t("隐私权相关政策");
                    LaunchHelper.launchWebActivity(
                        ApiConstant.PRIVACY_POLICY_SERVER
                    )
                }

                override fun updateDrawState(ds: TextPaint) {
                    ds.color = ContextCompat.getColor(this@LoginActivity, R.color.c_3378ff)
                    ds.isUnderlineText = false
                }
            })
            .build()

        isDebugModel().yes {
//            mViewContentBinding.phoneEdt.setText("18925252393")
            mViewContentBinding.phoneEdt.setText("18126467401")
            mViewContentBinding.privacyAgreementCkb.initChecked(true)
        }
    }


    override fun initEvents() {
        super.initEvents()

        mViewContentBinding.phoneEdt.addTextChangedListener(object : TextWatcher {
            override fun onTextChanged(
                s: CharSequence, start: Int, before: Int,
                count: Int
            ) {
//                    //s:变化后的所有字符
//                    Log.i("Seachal:","变化:"+s+";"+start+";"+before+";"+count);
            }

            override fun beforeTextChanged(
                s: CharSequence, start: Int, count: Int,
                after: Int
            ) {
//                    //s:变化前的所有字符； start:字符开始的位置； count:变化前的总字节数；after:变化后的字节数
//                    Log.i("Seachal:","变化前:"+s+";"+start+";"+count+";"+after);
            }

            override fun afterTextChanged(s: Editable) {
//                    //S：变化后的所有字符；start：字符起始的位置；before: 变化之前的总字节数；count:变化后的字节数
//                    Log.i("Seachal:","变化后:"+s+";");

                //如果改变了，并且文本长度>0
                if (!TextUtils.isEmpty(s.toString())) {
                    mViewContentBinding.deleteBtn.visibility = View.VISIBLE
                } else {
                    mViewContentBinding.deleteBtn.visibility = View.GONE
                }

                mViewContentBinding.loginTv.isEnabled = !TextUtils.isEmpty(s.toString())
            }
        })

        mViewContentBinding.loginTv.setOnClickListener(onClick = this)
        mViewContentBinding.areaCodeHint.setOnClickListener(onClick = this)
        mViewContentBinding.deleteBtn.setOnClickListener(onClick = this)
    }


    override fun onClick(v: View?) {
        when (v) {
            mViewContentBinding.deleteBtn -> mViewContentBinding.phoneEdt.text.clear()

            mViewContentBinding.loginTv -> {
                mPhone = mViewContentBinding.phoneEdt.text?.toString()?.trim() ?: ""
                if (TextUtils.isEmpty(mPhone)) {
                    showToast(R.string.common_please_input_phone)
                    return
                }
                Constants.curPhone = mPhone
                requestTransTer()
            }

        }
    }

    /**
     * 获取验证码
     */
    private fun requestTransTer() {
        mViewContentBinding.privacyAgreementCkb.isChecked().no {
            ToastUtils.showToast(R.string.common_read_agreement_tip)
            return
        }
        showDialogLoading()
        mViewModel.requestVerCode(mPhone, 4, mCountry)
            .observe(this) {
                dismissLoadingDialog()
                it.isSuccess().yes {
                    showToast("验证码发送成功！")
                    toVerificationCodeInputActivity()
                }.otherwise {
                    if (it.Code==115){
                        toVerificationCodeInputActivity()
                    }
                    if (it.Code==500 && isDebugModel()){
                        toVerificationCodeInputActivity()
                    }
                    showToast(it.Message)
                }
            }
    }

    private fun toVerificationCodeInputActivity(){
        val bundle = Bundle()
        bundle.putParcelable(KeyBundle.BUNDLE_KEY, commonMessageRelayModel)
        bundle.putString(KeyBundle.EXPAND_DATA, mPhone)
        startActivity<VerificationCodeInputActivity>(bundle,false)
    }

}